<template>
  <!-- 头部问好条 -->
  <div>
    <ContentWrap>
      <el-skeleton :loading="loading" animated>
        <div class="welcome-header">
          <div class="welcome-left">
            <el-avatar :src="avatar" :size="48" class="user-avatar">
              <img src="@/assets/imgs/avatar.gif" alt="" />
            </el-avatar>
            <div class="welcome-info">
              <div class="welcome-text">
                {{ t('workplace.welcome') }} {{ username }} {{ t('workplace.happyDay') }}
              </div>
              <div class="welcome-subtitle"> 今天是个美好的一天，开始您的工作吧！ </div>
            </div>
          </div>

          <div class="header-actions">
            <el-button class="action-btn" @click="toInstructions">
              <el-icon><Document /></el-icon>
              文档中心
            </el-button>
            <el-button type="success" class="action-btn" @click="wentUrl">
              <el-icon><User /></el-icon>
              账户中心
            </el-button>
            <el-button
              type="primary"
              class="action-btn"
              @click="router.push('/user/profile/systemBuy')"
            >
              <el-icon><ShoppingCart /></el-icon>
              购买套餐
            </el-button>
          </div>
        </div>
      </el-skeleton>
    </ContentWrap>
  </div>

  <!-- 内容区域 -->
  <div class="main-content">
    <!-- 待办客资 -->
    <ContentWrap shadow="never" class="content-card todo-section">
      <div class="section-header">
        <div class="section-title">
          <el-icon class="title-icon"><Bell /></el-icon>
          {{ t('workplace.toDo') }}
        </div>
      </div>
      <div class="todo-grid">
        <div
          v-for="(item, index) in toDo"
          :key="`dynamics-${index}`"
          @click="handleTodo(item.menu)"
          class="todo-card"
          :class="{ 'has-count': item.count > 0 }"
        >
          <div class="todo-icon">
            <img :src="item.icon" alt="" />
          </div>
          <div class="todo-content">
            <CountTo
              :endVal="item.count"
              :class="{ highlight: item.count > 0 }"
              class="todo-count"
            />
            <span class="todo-name" :class="{ highlight: item.count > 0 }">
              {{ item.name }}
            </span>
          </div>
        </div>
      </div>
    </ContentWrap>

    <!-- 仪表盘 -->
    <ContentWrap shadow="never" class="content-card dashboard-section">
      <div class="section-header">
        <div class="section-title">
          <el-icon class="title-icon"><DataAnalysis /></el-icon>
          {{ t('workplace.dashboard') }}
        </div>
        <div class="dashboard-controls">
          <el-tree-select
            v-model="queryParams.deptId"
            :data="deptList"
            :props="defaultProps"
            check-strictly
            class="control-select"
            node-key="id"
            placeholder="请选择归属部门"
            @change="queryParams.userId = undefined"
          />

          <el-select
            v-model="queryParams.userId"
            class="control-select"
            clearable
            placeholder="员工"
          >
            <el-option
              v-for="(user, index) in userListByDeptId"
              :key="index"
              :label="user.nickname"
              :value="user.id"
            />
          </el-select>

          <el-dropdown trigger="click" placement="bottom-end" v-if="custom == false">
            <el-button class="date-picker-btn">
              <span>{{ datePickerTime }}</span>
              <el-icon><Calendar /></el-icon>
            </el-button>
            <template #dropdown>
              <div class="date-dropdown">
                <el-button
                  v-for="button in dateBtn"
                  :key="button.dateType"
                  :type="button.type"
                  text
                  :disabled="button.disabled"
                  @click="pickDate(button.dateType)"
                  class="date-btn"
                >
                  {{ button.dateType }}
                </el-button>
              </div>
              <div class="custom-date" @click="handleCustom">自定义</div>
            </template>
          </el-dropdown>

          <div v-if="custom" class="custom-picker">
            <el-date-picker
              ref="datepicke"
              v-model="valuepicker"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="datetimerange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @blur="pickChange"
              @change="pickChange"
            />
          </div>

          <el-button type="primary" @click="handleQuery" class="search-btn">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetQuery" class="reset-btn">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </div>
      </div>

      <el-skeleton :loading="loading2" animated>
        <div class="dashboard-grid">
          <div class="data-card clue-card">
            <div class="card-header">
              <el-icon class="card-icon"><Opportunity /></el-icon>
              <span class="card-title">线索数据</span>
            </div>
            <div class="card-content">
              <div class="data-row">
                <div class="data-item">
                  <span class="data-label">负责的线索</span>
                  <span class="data-value">{{ clueCountData.ownClueCount }}</span>
                </div>
                <div class="data-item">
                  <span class="data-label">参与的线索</span>
                  <span class="data-value">{{ clueCountData.partClueCount }}</span>
                </div>
              </div>
              <div class="data-row">
                <div class="data-item">
                  <span class="data-label">已跟进线索</span>
                  <span class="data-value">{{ clueCountData.followedClueCount }}</span>
                </div>
                <div class="data-item">
                  <span class="data-label">已转化线索</span>
                  <span class="data-value">{{ clueCountData.transClueCount }}</span>
                </div>
              </div>
            </div>
          </div>

          <div class="data-card customer-card">
            <div class="card-header">
              <el-icon class="card-icon"><User /></el-icon>
              <span class="card-title">客户数据</span>
            </div>
            <div class="card-content">
              <div class="data-row">
                <div class="data-item">
                  <span class="data-label">负责的客户</span>
                  <span class="data-value">{{ customerCountData.ownCustomerCount }}</span>
                </div>
                <div class="data-item">
                  <span class="data-label">参与的客户</span>
                  <span class="data-value">{{ customerCountData.partCustomerCount }}</span>
                </div>
              </div>
              <div class="data-row">
                <div class="data-item">
                  <span class="data-label">已跟进客户</span>
                  <span class="data-value">{{ customerCountData.followedCustomerCount }}</span>
                </div>
                <div class="data-item">
                  <span class="data-label">已成交客户</span>
                  <span class="data-value">{{ customerCountData.dealCustomerCount }}</span>
                </div>
              </div>
            </div>
          </div>

          <div class="data-card business-card">
            <div class="card-header">
              <el-icon class="card-icon"><TrendCharts /></el-icon>
              <span class="card-title">商机数据</span>
            </div>
            <div class="card-content">
              <div class="data-row">
                <div class="data-item">
                  <span class="data-label">新增商机数</span>
                  <span class="data-value">{{ businessCountData.businessCount }}</span>
                </div>
                <div class="data-item">
                  <span class="data-label">商机总金额</span>
                  <span class="data-value">{{ businessCountData.businessAmountSum }}</span>
                </div>
              </div>
              <div class="data-row">
                <div class="data-item">
                  <span class="data-label">新增合同数</span>
                  <span class="data-value">{{ businessCountData.contractCount }}</span>
                </div>
                <div class="data-item">
                  <span class="data-label">合同总金额</span>
                  <span class="data-value">{{ businessCountData.contractAmountSum }}</span>
                </div>
              </div>
            </div>
          </div>

          <div class="data-card call-card">
            <div class="card-header">
              <el-icon class="card-icon"><Phone /></el-icon>
              <span class="card-title">外呼数据</span>
            </div>
            <div class="card-content">
              <div class="data-row">
                <div class="data-item">
                  <span class="data-label">外呼次数</span>
                  <span class="data-value">{{ callCountData.callNumber }}</span>
                </div>
                <div class="data-item">
                  <span class="data-label">接通次数</span>
                  <span class="data-value">{{ callCountData.successNumber }}</span>
                </div>
              </div>
            </div>
          </div>

          <div class="data-card enterprise-card">
            <div class="card-header">
              <el-icon class="card-icon"><OfficeBuilding /></el-icon>
              <span class="card-title">企业数据</span>
            </div>
            <div class="card-content">
              <div class="data-row">
                <div class="data-item">
                  <span class="data-label">领取企业数</span>
                  <span class="data-value">{{ entCountData.receiveNumber }}</span>
                </div>
                <div class="data-item">
                  <span class="data-label">跟进企业数</span>
                  <span class="data-value">{{ entCountData.followNumber }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-skeleton>
    </ContentWrap>

    <!-- 快捷入口 -->
    <ContentWrap shadow="never" class="content-card shortcut-section">
      <div class="section-header">
        <div class="section-title">
          <el-icon class="title-icon"><Grid /></el-icon>
          {{ t('workplace.shortcutOperation') }}
        </div>
      </div>
      <div class="shortcut-grid">
        <div
          v-for="(item, index) in shortcut"
          :key="`dynamics-${index}`"
          @click="openShortcut(item.url)"
          class="shortcut-card"
        >
          <div class="shortcut-icon" :class="`icon-${index + 1}`">
            <Icon :icon="item.icon" />
          </div>
          <span class="shortcut-name">{{ item.name }}</span>
        </div>
      </div>
    </ContentWrap>
  </div>

  <!-- 弹窗组件保持不变 -->
  <CustomerForm ref="customerFormRef" />
  <ContactForm ref="contactFormRef" />
  <ClueForm ref="clueFormRef" />
  <BusinessForm ref="businessFormRef" />

  <div class="test">
    <Dialog
      v-model="showToDoList"
      :before-close="handleCloseToDoList"
      :title="menuTitle[leftMenu]"
      width="80%"
      append-to="test"
    >
      <CustomerTodayContactList v-if="leftMenu === 'customerTodayContact'" />
      <ClueFollowList v-if="leftMenu === 'clueFollow'" />
      <OverdueContactClueList v-if="leftMenu === 'overdueContactClue'" />
      <ContractAuditList v-if="leftMenu === 'contractAudit'" />
      <ReceivableAuditList v-if="leftMenu === 'receivableAudit'" />
      <ContractRemindList v-if="leftMenu === 'contractRemind'" />
      <CustomerFollowList v-if="leftMenu === 'customerFollow'" />
      <CustomerPutPoolRemindList
        v-if="leftMenu === 'customerPutPoolRemind'"
        :module-count-obj="moduleCountObj"
      />
      <ReceivablePlanRemindList v-if="leftMenu === 'receivablePlanRemind'" />
      <OverdueContactList v-if="leftMenu === 'overdueContact'" />
      <CluePutPoolRemindList
        v-if="leftMenu === 'cluePutPoolRemind'"
        :module-count-obj="moduleCountObj"
      />
    </Dialog>
  </div>
</template>
<script lang="ts" setup>
import { set } from 'lodash-es'
import dayjs from 'dayjs'
import { EChartsOption } from 'echarts'
import CustomerForm from '../crm/customer/CustomerForm.vue'
import ContactForm from '../crm/contact/ContactForm.vue'
import ClueForm from '../crm/clue/ClueForm.vue'
import BusinessForm from '../crm/business/BusinessForm.vue'
import { useUserStore } from '@/store/modules/user'
import type { WorkplaceTotal, Notice, Shortcut } from './types'
import { pieOptions, barOptions } from './echarts-data'
import {
  Calendar,
  Odometer,
  Finished,
  Position,
  Expand,
  Document,
  User,
  ShoppingCart,
  Bell,
  DataAnalysis,
  Search,
  Refresh,
  Opportunity,
  TrendCharts,
  Phone,
  OfficeBuilding,
  Grid
} from '@element-plus/icons-vue'
import getDateFn from './getDateFn'
import CustomerFollowList from '../crm/backlog/components/CustomerFollowList.vue'
import CustomerTodayContactList from '../crm/backlog/components/CustomerTodayContactList.vue'
import OverdueContactList from '../crm/backlog/components/OverdueContactList.vue'
import CustomerPutPoolRemindList from '../crm/backlog/components/CustomerPutPoolRemindList.vue'
import ClueFollowList from '../crm/backlog/components/ClueFollowList.vue'
import CluePutPoolRemindList from '../crm/backlog/components/CluePutPoolRemindList.vue'
import OverdueContactClueList from '../crm/backlog/components/OverdueContactClueList.vue'
import ContractAuditList from '../crm/backlog/components/ContractAuditList.vue'
import ContractRemindList from '../crm/backlog/components/ContractRemindList.vue'
import ReceivablePlanRemindList from '../crm/backlog/components/ReceivablePlanRemindList.vue'
import ReceivableAuditList from '../crm/backlog/components/ReceivableAuditList.vue'
import * as CustomerApi from '@/api/crm/customer'
import * as ClueApi from '@/api/crm/clue'
import * as ContractApi from '@/api/crm/contract'
import * as ReceivableApi from '@/api/crm/receivable'
import * as ReceivablePlanApi from '@/api/crm/receivable/plan'
import * as HomeDataApi from '@/api/home'
import * as DeptApi from '@/api/system/dept'
import * as UserApi from '@/api/system/user'
import { defaultProps, handleTree } from '@/utils/tree'
import { userSelector } from '@/utils/deptUserSelect'

const router = useRouter()

defineOptions({ name: 'Home' })

const queryParams = reactive({
  deptId: useUserStore().getUser.deptId,
  userId: undefined
})
const deptId = ref()
const deptList = ref<Tree[]>([]) // 部门树形结构
const userList = ref<UserApi.UserVO[]>([]) // 全量用户清单

/** 根据选择的部门筛选员工清单 */
const userListByDeptId = computed(() => {
  return userSelector(userList.value, deptList.value, queryParams.deptId)
})

/*企业中心*/
const wentUrl = () => {
  router.push('/user/system')
}

/** 文档中心 */
const toInstructions = () => {
  push('/user/instructions')
}
const { t } = useI18n()
const userStore = useUserStore()
const loading = ref(true)
const loading2 = ref(true)
const avatar = userStore.getUser.avatar
const username = userStore.getUser.nickname
const pieOptionsData = reactive<EChartsOption>(pieOptions) as EChartsOption
// 仪表盘
const projects = ref([
  {
    name: '销售简报',
    data: [
      {
        name: '新增客户',
        num: 0,
        icon: 'fa:user-plus'
      },
      {
        name: '已跟进客户',
        num: 0,
        icon: 'fa-solid:user-check'
      }
    ]
  },
  {
    name: '企业大数据',
    data: [
      {
        name: '领取企业',
        num: 0,
        icon: 'fa:address-card'
      },
      {
        name: '跟进次数',
        num: 0,
        icon: 'fa:address-book'
      }
    ]
  },
  {
    name: '外呼统计',
    data: [
      {
        name: '外呼次数',
        num: 0,
        icon: 'fa-solid:phone-alt'
      },
      {
        name: '接通次数',
        num: 0,
        icon: 'fa:volume-control-phone'
      }
    ]
  },
  {
    name: '商机成交',
    data: [
      {
        name: '新增商机',
        num: 0,
        icon: 'fa:archive'
      },
      {
        name: '商机金额',
        num: 0,
        icon: 'fa-solid:funnel-dollar'
      }
    ]
  }
])
// 本季
const getNowSeaon = () => {
  const currentMonth = dayjs().month() // 当前月份
  let startOfQuarter, endOfQuarter
  // 根据当前月份确定季度的开始和结束时间
  if (currentMonth < 3) {
    // 第一季度
    startOfQuarter = dayjs().startOf('year')
    endOfQuarter = dayjs().month(2).endOf('month')
  } else if (currentMonth < 6) {
    // 第二季度
    startOfQuarter = dayjs().month(3).startOf('month')
    endOfQuarter = dayjs().month(5).endOf('month')
  } else if (currentMonth < 9) {
    // 第三季度
    startOfQuarter = dayjs().month(6).startOf('month')
    endOfQuarter = dayjs().month(8).endOf('month')
  } else {
    // 第四季度
    startOfQuarter = dayjs().month(9).startOf('month')
    endOfQuarter = dayjs().endOf('year')
  }
  return [startOfQuarter.format('YYYY-MM-DD HH:mm:ss'), endOfQuarter.format('YYYY-MM-DD HH:mm:ss')]
}
// 上季
const getLasSeaon = () => {
  const currentMonth = dayjs().month() // 当前月份
  let startOfLastQuarter, endOfLastQuarter

  // 根据当前月份确定上个季度的开始和结束时间
  if (currentMonth < 3) {
    // 如果当前是第一季度
    startOfLastQuarter = dayjs().subtract(1, 'year').month(9).startOf('month')
    endOfLastQuarter = dayjs().subtract(1, 'year').month(11).endOf('month')
  } else if (currentMonth < 6) {
    // 如果当前是第二季度
    startOfLastQuarter = dayjs().month(0).startOf('month')
    endOfLastQuarter = dayjs().month(2).endOf('month')
  } else if (currentMonth < 9) {
    // 如果当前是第三季度
    startOfLastQuarter = dayjs().month(3).startOf('month')
    endOfLastQuarter = dayjs().month(5).endOf('month')
  } else {
    // 如果当前是第四季度
    startOfLastQuarter = dayjs().month(6).startOf('month')
    endOfLastQuarter = dayjs().month(8).endOf('month')
  }
  return [
    startOfLastQuarter.format('YYYY-MM-DD HH:mm:ss'),
    endOfLastQuarter.format('YYYY-MM-DD HH:mm:ss')
  ]
}
// 日期默认值
const datePickerTime = ref('请选择日期')
const dateBtn = [
  { type: '', dateType: '天', disabled: true },
  { type: '', dateType: '今天', disabled: false },
  { type: '', dateType: '昨天', disabled: false },
  { type: '', dateType: '周', disabled: true },
  { type: '', dateType: '本周', disabled: false },
  { type: '', dateType: '上周', disabled: false },
  { type: '', dateType: '月', disabled: true },
  { type: '', dateType: '本月', disabled: false },
  { type: '', dateType: '上月', disabled: false },
  { type: '', dateType: '季', disabled: true },
  { type: '', dateType: '本季', disabled: false },
  { type: '', dateType: '上季', disabled: false }
]
const time = ref('')
// 日期快捷键选择
function pickDate(type) {
  if (type == '今天') {
    datePickerTime.value =
      getDateFn.getDate() + ' 00:00:00' + ' ~ ' + getDateFn.getDate() + ' 23:59:59'
  } else if (type == '昨天') {
    datePickerTime.value =
      getDateFn.getDate(-1) + ' 00:00:00' + ' ~ ' + getDateFn.getDate(-1) + ' 23:59:59'
  } else if (type == '本周') {
    datePickerTime.value =
      getDateFn.getMonday('s') + ' 00:00:00' + ' ~ ' + getDateFn.getMonday('e') + ' 23:59:59'
  } else if (type == '上周') {
    datePickerTime.value =
      getDateFn.getMonday('s', -1) +
      ' 00:00:00' +
      ' ~ ' +
      getDateFn.getMonday('e', -1) +
      ' 23:59:59'
  } else if (type == '本月') {
    datePickerTime.value =
      getDateFn.getMonth('s', 0) + ' 00:00:00' + ' ~ ' + getDateFn.getMonth('e', 0) + ' 23:59:59'
  } else if (type == '上月') {
    datePickerTime.value =
      getDateFn.getMonth('s', -1) + ' 00:00:00' + ' ~ ' + getDateFn.getMonth('e', -1) + ' 23:59:59'
  } else if (type == '本季') {
    datePickerTime.value = getNowSeaon().join('~')
  } else if (type == '上季') {
    datePickerTime.value = getLasSeaon().join('~')
  }
}
const custom = ref(false)
const valuepicker = ref('')
const pickChange = () => {
  if (valuepicker.value[0] != undefined && valuepicker.value[1] != undefined) {
    datePickerTime.value = valuepicker.value[0] + ' ~ ' + valuepicker.value[1]
  }
  custom.value = false
  valuepicker.value = ''
}
const datepicke = ref('')
async function handleCustom() {
  custom.value = true
  await nextTick()
  datepicke.value.focus(true)
}

watch(
  () => datePickerTime.value,
  (val) => {
    time.value = val.split('~').map((i) => i.trim())
  },
  { immediate: true, deep: true }
)

const clueCountData = reactive({
  ownClueCount: 0,
  partClueCount: 0,
  followedClueCount: 0,
  transClueCount: 0
})
const customerCountData = reactive({
  ownCustomerCount: 0,
  partCustomerCount: 0,
  followedCustomerCount: 0,
  dealCustomerCount: 0
})
const businessCountData = reactive({
  businessCount: 0,
  businessAmountSum: 0,
  contractCount: 0,
  contractAmountSum: 0
})
const entCountData = reactive({
  receiveNumber: 0,
  followNumber: 0
})
const callCountData = reactive({
  callNumber: 0,
  successNumber: 0
})
const handleQuery = () => {
  getClueCountFn()
  getCustomerCountFn()
  getBusinessCountFn()
  getEntStatistics()
  getCallStatistics()
}
/** 查询线索数据 */
const getClueCountFn = async () => {
  if (time.value == '请选择日期') return
  loading2.value = true
  try {
    const data = await HomeDataApi.getClueCount({
      deptId: queryParams.deptId,
      userId: queryParams.userId,
      time: time.value
    })
    clueCountData.ownClueCount = data.ownClueCount
    clueCountData.partClueCount = data.partClueCount
    clueCountData.followedClueCount = data.followedClueCount
    clueCountData.transClueCount = data.transClueCount
  } finally {
    loading2.value = false
  }
}
/** 查询客户数据 */
const getCustomerCountFn = async () => {
  if (time.value == '请选择日期') return
  loading2.value = true
  try {
    const data = await HomeDataApi.getCustomerCount({
      deptId: queryParams.deptId,
      userId: queryParams.userId,
      time: time.value
    })
    customerCountData.ownCustomerCount = data.ownCustomerCount
    customerCountData.partCustomerCount = data.partCustomerCount
    customerCountData.followedCustomerCount = data.followedCustomerCount
    customerCountData.dealCustomerCount = data.dealCustomerCount
  } finally {
    loading2.value = false
  }
}
/** 查询商机数据 */
const getBusinessCountFn = async () => {
  if (time.value == '请选择日期') return
  loading2.value = true
  try {
    const data = await HomeDataApi.getBusinessCount({
      deptId: queryParams.deptId,
      userId: queryParams.userId,
      time: time.value
    })
    businessCountData.businessCount = data.businessCount
    businessCountData.businessAmountSum = data.businessAmountSum
    businessCountData.contractCount = data.contractCount
    businessCountData.contractAmountSum = data.contractAmountSum
  } finally {
    loading2.value = false
  }
}

/** 查询企业大数据 */
const getEntStatistics = async () => {
  if (time.value == '请选择日期') return
  loading2.value = true
  try {
    const data = await HomeDataApi.getEntStatistics({
      deptId: queryParams.deptId,
      userId: queryParams.userId,
      time: time.value
    })
    entCountData.receiveNumber = data.receiveNumber
    entCountData.followNumber = data.followNumber // 跟进
  } finally {
    loading2.value = false
  }
}

// /** 查询外呼统计 */
const getCallStatistics = async () => {
  if (time.value == '请选择日期') return
  loading2.value = true
  try {
    const data = await HomeDataApi.getCallStatistics({
      deptId: queryParams.deptId,
      userId: queryParams.userId,
      time: time.value
    })
    callCountData.callNumber = data.callNumber
    callCountData.successNumber = data.successNumber // 接通
  } finally {
    loading2.value = false
  }
}

const leftMenu = ref('customerTodayContact')
const todayContactCountClueCount = ref(0)
const overdueContactClueCount = ref(0)
const customerPutPoolRemindCount = ref(0)
const cluePutPoolRemindCount = ref(0)
const customerTodayContactCount = ref(0)
const contractRemindCount = ref(0)
const receivableAuditCount = ref(0)
const receivablePlanRemindCount = ref(0)
const overdueContactCount = ref(0)

const menuTitle = {
  customerTodayContact: '今日需跟进客户',
  clueFollow: '今日需跟进线索',
  contractRemind: '即将到期的合同',
  customerPutPoolRemind: '即将进入公海客户',
  overdueContact: '逾期未跟进客户',
  receivablePlanRemind: '需提醒的回款',
  cluePutPoolRemind: '即将进入公海线索',
  overdueContactClue: '逾期未跟进线索'
}
// 获取待办客资
let toDo = ref([
  {
    name: '今日需跟进客户',
    menu: 'customerTodayContact',
    icon: new URL(`../../assets/imgs/homIcon/lianxikehu.png`, import.meta.url),
    count: customerTodayContactCount
  },
  {
    name: '今日需跟进线索',
    menu: 'clueFollow',
    icon: new URL(`../../assets/imgs/homIcon/genjinxiansuo.png`, import.meta.url),
    count: todayContactCountClueCount
  },
  {
    name: '即将到期的合同',
    menu: 'contractRemind',
    icon: new URL(`../../assets/imgs/homIcon/daoqihetong.png`, import.meta.url),
    count: contractRemindCount
  },
  {
    name: '即将进入公海客户',
    menu: 'customerPutPoolRemind',
    icon: new URL(`../../assets/imgs/homIcon/jinggao.png`, import.meta.url),
    count: customerPutPoolRemindCount
  },

  {
    name: '逾期未跟进客户',
    menu: 'overdueContact',
    icon: new URL(`../../assets/imgs/homIcon/yuqi.png`, import.meta.url),
    count: overdueContactCount
  },

  {
    name: '逾期未跟进线索',
    menu: 'overdueContactClue',
    icon: new URL(`../../assets/imgs/homIcon/yuqi.png`, import.meta.url),
    count: overdueContactClueCount
  },
  {
    name: '需提醒的回款',
    menu: 'receivablePlanRemind',
    icon: new URL(`../../assets/imgs/homIcon/huikuantixing.png`, import.meta.url),
    count: receivablePlanRemindCount
  },
  {
    name: '即将进入公海线索',
    menu: 'cluePutPoolRemind',
    icon: new URL(`../../assets/imgs/homIcon/jinggao.png`, import.meta.url),
    count: cluePutPoolRemindCount
  }
])
const moduleCountObj = ref({})
// 获取count
const getToDoCount = () => {
  CustomerApi.getTodayContactCustomerCount().then(
    (count) => (customerTodayContactCount.value = count)
  )
  CustomerApi.getPutPoolRemindCustomerCount().then((res) => {
    if (res != null) {
      moduleCountObj.value = res
      Object.values(res).forEach((val) => {
        customerPutPoolRemindCount.value += val
      })
    } else {
      moduleCountObj.value = 0
    }
  })
  ClueApi.getCluePutPoolRemindCount().then((res) => {
    if (res != null) {
      moduleCountObj.value = res
      Object.values(res).forEach((val) => {
        cluePutPoolRemindCount.value += val
      })
    } else {
      moduleCountObj.value = 0
    }
  })
  CustomerApi.getOverdueContactCount().then((count) => (overdueContactCount.value = count))
  ClueApi.getTodayContactCountClueCount().then(
    (count) => (todayContactCountClueCount.value = count)
  )
  ClueApi.getTodayOverdueCountClueCount().then((count) => (overdueContactClueCount.value = count))
  ContractApi.getRemindContractCount().then((count) => (contractRemindCount.value = count))
  ReceivableApi.getAuditReceivableCount().then((count) => (receivableAuditCount.value = count))
  ReceivablePlanApi.getReceivablePlanRemindCount().then(
    (count) => (receivablePlanRemindCount.value = count)
  )
}
const showToDoList = ref(false)
// 点击某项待办
const handleTodo = (title) => {
  showToDoList.value = true
  leftMenu.value = title
}
// 关闭待办弹框
const handleCloseToDoList = () => {
  showToDoList.value = false
}
/** 激活时 */
onActivated(async () => {
  getToDoCount()
})

/** 初始化 */
onMounted(async () => {
  getToDoCount()
})

// 获取快捷入口
let shortcut = reactive<Shortcut[]>([])

const getShortcut = async () => {
  const data = [
    {
      name: '新建线索',
      icon: 'fa:lightbulb-o',
      url: 'addClue'
    },
    {
      name: '新建客户',
      icon: 'fa-solid:user-plus',
      url: 'addCustomer'
    },
    {
      name: '新建联系人',
      icon: 'fa:address-book',
      url: 'addContact'
    },
    {
      name: '新建商机',
      icon: 'fa:briefcase',
      url: 'addBusiness'
    },
    {
      name: '待我审批',
      icon: 'fa:check-square',
      url: 'pushTodo'
    },
    {
      name: '发起OA流程',
      icon: 'fa:ils',
      url: 'pushOA'
    }
  ]
  shortcut = Object.assign(shortcut, data)
}
// 新增客户
const customerFormRef = ref()
// 新增联系人
const contactFormRef = ref()
// 新增线索
const clueFormRef = ref()
// 新建商机
const businessFormRef = ref()

const { push } = useRouter()

const openShortcut = (shortcut) => {
  // 新增客户
  if (shortcut == 'addCustomer') {
    customerFormRef.value.open('create')
  }
  // 新增联系人
  else if (shortcut == 'addContact') {
    contactFormRef.value.open('create')
  }
  //新增线索
  else if (shortcut == 'addClue') {
    clueFormRef.value.open('create')
  }
  //新建商机
  else if (shortcut == 'addBusiness') {
    businessFormRef.value.open('create')
  }
  //跳转待我审批
  else if (shortcut == 'pushTodo') {
    push({ name: 'BpmTodoTask' })
  }
  //跳转发起OA流程
  else if (shortcut == 'pushOA') {
    push({ name: 'BpmProcessInstanceCreate' })
  }
}

// 获取通知公告
let notice = reactive<Notice[]>([])
const getNotice = async () => {
  const data = [
    {
      title: '系统升级版本',
      author: '我',
      type: '通知',
      content: 'xxxxxxxxxxxxxx',
      keys: ['通知', '升级'],
      date: new Date()
    },
    {
      title: '系统凌晨维护',
      type: '公告',
      author: '我',
      content: 'xxxxxxxxxxxxxx',
      keys: ['公告', '维护'],
      date: new Date()
    },
    {
      title: '系统升级版本',
      type: '通知',
      author: '我',
      content: 'xxxxxxxxxxxxxx',
      keys: ['通知', '升级'],
      date: new Date()
    }
  ]
  notice = Object.assign(notice, data)
}

// 用户来源
const getUserAccessSource = async () => {
  const data = [
    { value: 335, name: 'analysis.directAccess' },
    { value: 310, name: 'analysis.mailMarketing' },
    { value: 234, name: 'analysis.allianceAdvertising' },
    { value: 135, name: 'analysis.videoAdvertising' },
    { value: 1548, name: 'analysis.searchEngines' }
  ]
  set(
    pieOptionsData,
    'legend.data',
    data.map((v) => t(v.name))
  )
  pieOptionsData!.series![0].data = data.map((v) => {
    return {
      name: t(v.name),
      value: v.value
    }
  })
}
const barOptionsData = reactive<EChartsOption>(barOptions) as EChartsOption

// 周活跃量
const getWeeklyUserActivity = async () => {
  const data = [
    { value: 13253, name: 'analysis.monday' },
    { value: 34235, name: 'analysis.tuesday' },
    { value: 26321, name: 'analysis.wednesday' },
    { value: 12340, name: 'analysis.thursday' },
    { value: 24643, name: 'analysis.friday' },
    { value: 1322, name: 'analysis.saturday' },
    { value: 1324, name: 'analysis.sunday' }
  ]
  set(
    barOptionsData,
    'xAxis.data',
    data.map((v) => t(v.name))
  )
  set(barOptionsData, 'series', [
    {
      name: t('analysis.activeQuantity'),
      data: data.map((v) => v.value),
      type: 'bar'
    }
  ])
}

const getAllApi = async () => {
  await Promise.all([getNotice(), getShortcut(), getUserAccessSource(), getWeeklyUserActivity()])
  loading.value = false
}

getAllApi()

/** 初始化 **/
onMounted(async () => {
  deptList.value = handleTree(await DeptApi.getSimpleDeptList())
  userList.value = handleTree(await UserApi.getSimpleUserList())
  await pickDate('今天')
  await handleQuery()
})
</script>

<style lang="scss" scoped>
/* 全局样式重置 */
.main-content {
  margin-top: 16px;
  overflow: hidden;
  background: var(--app-content-bg-color);
}

.content-card {
  margin-bottom: 16px;
  border-radius: 12px;
  background: #ffffff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  border: 1px solid #f0f0f0;
  transition: all 0.3s ease;
}

.content-card:hover {
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transform: translateY(-2px);
}

/* 头部欢迎区域 */
.welcome-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px;
  background: linear-gradient(135deg, #97a5e2 0%, #7db5db 100%);
  border-radius: 12px;
  color: white;
  position: relative;
  overflow: hidden;
}

.welcome-header::before {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  width: 200px;
  height: 200px;
  background: radial-gradient(circle, rgba(255, 255, 255, 0.1) 0%, transparent 70%);
  border-radius: 50%;
  transform: translate(50%, -50%);
}

.welcome-left {
  display: flex;
  align-items: center;
  gap: 16px;
  z-index: 1;
}

.user-avatar {
  border: 3px solid rgba(255, 255, 255, 0.3);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.welcome-info {
  .welcome-text {
    font-size: 20px;
    font-weight: 600;
    margin-bottom: 4px;
  }

  .welcome-subtitle {
    font-size: 14px;
    opacity: 0.9;
  }
}

.header-actions {
  display: flex;
  gap: 12px;
  z-index: 1;
}

.action-btn {
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.2s ease;
}

.action-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 区域标题 */
.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
  padding: 0 4px;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
}

.title-icon {
  color: #0052cc;
  font-size: 20px;
}

/* 待办事项区域 */
.todo-section {
  padding: 24px;
}

.todo-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 16px;
}

.todo-card {
  display: flex;
  align-items: center;
  padding: 20px;
  background: #fafbfc;
  border-radius: 10px;
  border: 2px solid transparent;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.todo-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(0, 82, 204, 0.05), transparent);
  transition: left 0.5s ease;
}

.todo-card:hover {
  background: #f0f7ff;
  border-color: #0052cc;
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 82, 204, 0.1);
}

.todo-card:hover::before {
  left: 100%;
}

.todo-card.has-count {
  background: linear-gradient(135deg, #fff7ed 0%, #ffedd5 100%);
  border-color: #f97316;
}

.todo-card.has-count:hover {
  background: linear-gradient(135deg, #ffedd5 0%, #fed7aa 100%);
  box-shadow: 0 4px 16px rgba(249, 115, 22, 0.2);
}

.todo-icon {
  width: 56px;
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(0, 82, 204, 0.1);
  border-radius: 12px;
  margin-right: 16px;
  transition: all 0.3s ease;
}

.todo-card.has-count .todo-icon {
  background: rgba(249, 115, 22, 0.1);
}

.todo-icon img {
  width: 28px;
  height: 28px;
}

.todo-content {
  flex: 1;
}

.todo-count {
  font-size: 28px;
  font-weight: 700;
  color: #6b7280;
  display: block;
  margin-bottom: 4px;
  transition: all 0.3s ease;
}

.todo-count.highlight {
  color: #f97316;
}

.todo-name {
  font-size: 14px;
  color: #6b7280;
  font-weight: 500;
  transition: all 0.3s ease;
}

.todo-name.highlight {
  color: #f97316;
  font-weight: 600;
}

/* 仪表盘区域 */
.dashboard-section {
  padding: 24px;
}

.dashboard-controls {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.control-select {
  width: 200px;
}

.date-picker-btn {
  min-width: 160px;
  justify-content: space-between;
}

.custom-picker {
  width: 380px;
}

.search-btn,
.reset-btn {
  border-radius: 6px;
}

.date-dropdown {
  display: grid;
  width: 260px;
  height: 222px;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(4, 1fr);
  justify-items: center;
  grid-gap: 8px;
  padding: 16px;
}

.date-btn {
  width: 90%;
  height: 36px;
  border-radius: 6px;
  font-size: 13px;
}

.custom-date {
  height: 40px;
  font-size: 14px;
  line-height: 40px;
  color: #0052cc;
  text-align: center;
  cursor: pointer;
  border-top: 1px solid #e5e7eb;
  transition: all 0.2s ease;
}

.custom-date:hover {
  background-color: #f3f4f6;
}

/* 数据卡片网格 */
.dashboard-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.data-card {
  background: #ffffff;
  border-radius: 12px;
  padding: 24px;
  border: 1px solid #f0f0f0;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.data-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 4px;
  height: 100%;
  transition: all 0.3s ease;
}

.data-card:hover {
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transform: translateY(-2px);
}

.clue-card::before {
  background: #8b5cf6;
}
.customer-card::before {
  background: #06b6d4;
}
.business-card::before {
  background: #f59e0b;
}
.call-card::before {
  background: #ef4444;
}
.enterprise-card::before {
  background: #10b981;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 20px;
}

.card-icon {
  font-size: 24px;
}

.clue-card .card-icon {
  color: #8b5cf6;
}
.customer-card .card-icon {
  color: #06b6d4;
}
.business-card .card-icon {
  color: #f59e0b;
}
.call-card .card-icon {
  color: #ef4444;
}
.enterprise-card .card-icon {
  color: #10b981;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
}

.card-content {
  .data-row {
    display: flex;
    justify-content: space-between;
    margin-bottom: 16px;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .data-item {
    flex: 1;

    .data-label {
      display: block;
      font-size: 13px;
      color: #6b7280;
      margin-bottom: 4px;
    }

    .data-value {
      font-size: 20px;
      font-weight: 600;
      color: #1f2937;
    }
  }
}

/* 快捷入口区域 */
.shortcut-section {
  padding: 24px;
}

.shortcut-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
  gap: 20px;
}

.shortcut-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 24px 16px;
  background: #fafbfc;
  border-radius: 12px;
  border: 2px solid transparent;
  cursor: pointer;
  transition: all 0.3s ease;
  text-align: center;
}

.shortcut-card:hover {
  background: #f0f7ff;
  border-color: #0052cc;
  transform: translateY(-4px);
  box-shadow: 0 8px 25px rgba(0, 82, 204, 0.15);
}

.shortcut-icon {
  width: 56px;
  height: 56px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 12px;
  font-size: 24px;
  color: white;
  transition: all 0.3s ease;
}

.shortcut-card:hover .shortcut-icon {
  transform: scale(1.1);
}

.icon-1 {
  background: linear-gradient(135deg, #97a5e2 0%, #7db5db 100%);
}
.icon-2 {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}
.icon-3 {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}
.icon-4 {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}
.icon-5 {
  background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
}
.icon-6 {
  background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
}

.shortcut-name {
  font-size: 14px;
  font-weight: 500;
  color: #374151;
  transition: all 0.3s ease;
}

.shortcut-card:hover .shortcut-name {
  color: #0052cc;
  font-weight: 600;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .dashboard-grid {
    grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  }

  .todo-grid {
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  }
}

@media (max-width: 768px) {
  .welcome-header {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }

  .dashboard-controls {
    flex-direction: column;
    align-items: stretch;
  }

  .control-select {
    width: 100%;
  }

  .dashboard-grid {
    grid-template-columns: 1fr;
  }

  .todo-grid {
    grid-template-columns: 1fr;
  }

  .shortcut-grid {
    grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
  }
}

/* 保持原有的一些必要样式 */
.text-16px,
.text-15px {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.panel,
.todo,
.quick {
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

/* 对话框样式 */
:deep(.el-dialog__body) {
  padding: 10px 10px 1px;
  background: #f5f5f5;
}

:deep(.el-dialog__header) {
  padding: 0;
}

/* Element Plus 组件样式覆盖 */
:deep(.el-card__header) {
  height: 42px;
  padding: 0 20px;
}

:deep(.el-input__icon) {
  display: none;
}

:deep(.el-button--primary) {
  background-color: #0052cc;
  border-color: #0052cc;
}

:deep(.el-button--primary:hover) {
  background-color: #1d4ed8;
  border-color: #1d4ed8;
}
</style>
